﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Commander.Models.Home;
using System.Web.Routing;
using Commander.DataLayer.Repositories;
using Commander.Models.Dashboard;
using Gendarme;
using System.IO;

namespace Commander.Controllers {
  public class HomeController : Controller {

    public IFormsAuthenticationService FormsService { get; set; }
    public IMembershipService MembershipService { get; set; }
    private ICommanderUserRepository userRepo;
    protected override void Initialize(RequestContext requestContext) {

      //TODO: remove the line below once moving to production
      new DemoDataHelper().InsertData();

      if (userRepo == null) {
        userRepo = new CommanderUserRepository();
      }

      if (FormsService == null) { FormsService = new FormsAuthenticationService(); }
      if (MembershipService == null) { MembershipService = new AccountMembershipService(userRepo); }

      base.Initialize(requestContext);
    }

    public ActionResult Index() {
      return View();
    }

    public ActionResult Help() {
      return View();
    }

    public ActionResult Contact() {
      return View();
    }

    public ActionResult LogOn() {
      ViewData["copyright"] = "Copyright © 2011-" + DateTime.Now.Year + " Software Engineering Research Group @ Drexel University";
      return View();
    }

    [HttpPost]
    public ActionResult LogOn(LogOnModel model, string returnUrl) {
      if (ModelState.IsValid) {
        if (MembershipService.ValidateUser(model.UserName, model.Password)) {
          FormsService.SignIn(model.UserName, model.RememberMe);
          if (!String.IsNullOrEmpty(returnUrl)) {
            return Redirect(returnUrl);
          }
          else {
            Commander.Models.Dashboard.UserDashboardModel userDash = CreateUserDashboarModel(model);
            TempData["user"] = userDash;
            return RedirectToAction("Index", "Dashboard");
          }
        }
        else {
          ModelState.AddModelError("", "The user name or password provided is incorrect.");
        }
      }

      // If we got this far, something failed, redisplay form
      return View(model);
    }

    private UserDashboardModel CreateUserDashboarModel(LogOnModel model) {
      return new Models.Dashboard.UserDashboardModel {
        UserId = model.UserName,
        Projects = userRepo.GetProjectConfig(model.UserName, model.Password).Select(e =>
          new ProjectModel {
            Name = e.Name,
            ProjectType = e.Type.ToString(),
            OwnerId=model.UserName
          }).ToList()
      };
    }

    public ActionResult LogOff() {
      FormsService.SignOut();

      return RedirectToAction("LogOn");
    }
  }
}
